<template>
  <base-breadcrumb :title="$route.meta.title">
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel !==0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading">
        <!-- 分包 -->
        <div v-if="form.mdBelongTo === 'SUB'">
          <!-- 项目分包计量设备信息 -->
          <a-card :bordered="false">
            <title-name title="项目分包计量设备信息"></title-name>
            <custom-form
              :is-emit="false"
              :disabled="editModel===0"
              editModel="''"
              :formList="formList"
              :form="form"
              :formComponents="$refs"
            >
              <template slot="projectPlanName">
                  <a-input
                    v-model="form.projectPlanName"
                    disabled
                    class="chioseInput"
                    style="width: calc(100% - 70px)"
                    placeholder="请选择设所属配置计划"
                  />
                  <a-button class="chioseBtn" :disabled="editModel===0 || !form.mdModelId" type="primary" @click="chioseBtn">
                    选择
                  </a-button>
              </template>
            </custom-form>
          </a-card>
          <!-- 计量设备检定记录 -->
          <equipment-verification-record-module v-if="editModel === 0" :queryParam="verificationRecordQuery"></equipment-verification-record-module>
        </div>
        <!-- 自有 -->
        <own-equipment-info v-if="form.mdBelongTo === 'OWN'" :form="form" :queryParam="verificationRecordQuery"></own-equipment-info>
        <!-- 页脚操作栏 -->
        <div class="btn_box page-btn-right-top">
          <a-button :loading="loading" v-if="editModel !== 0" type="primary" class="button_right" @click="handleSubmit"
            >提交</a-button
          >
          <a-button v-if="checkVisibleInDetail" type="primary" @click="closePage">关闭</a-button>
        </div>
      </a-spin>
    </a-form-model>
    <!-- 所属配置计划 -->
    <selectedConfigPlan
        v-if="selectedConfigPlanVisible"
        :visible.sync="selectedConfigPlanVisible"
        :form="form"
        @handelShow="handelShow"
        @handleClick="handleModalClick"
      />
  </base-breadcrumb>
</template>

<script>
import UploadList from '@/components/UploadList'
import { addItem, editItem, detailsItem, generateMdCode} from '@/api/quality/projectMeterageEquipmentAccount'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
import Selector from '@/components/Select/Selector'
import { getSubcontractorsList } from '@/api/subcontractors/standing'
import { equipmentStatusArr, equipmentClassArr, checkType, equipmentBelongToArr, checkStatusArr} from '@/views/quality/equipmentManagement/constant/dictionary.js'
import selectedConfigPlan from './components/selectedConfigPlan'
import ownEquipmentInfo from './components/ownEquipmentInfo'
import equipmentVerificationRecordModule from '@/views/quality/equipmentManagement/module/equipmentVerificationRecord/index'
import moment from 'moment';
import equipmentBsic from '@/api/quality/equipmentNameManagement' // api
import dataFilter from '@/views/quality/equipmentManagement/constant/dataFilter.js'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: { selectedConfigPlan, equipmentVerificationRecordModule, ownEquipmentInfo},
  data() {
    return {
      loading: false, // 提交按钮loding
      editModel: 2, // 操作状态:0 查看;1 编辑;2 新增
      form: {
        annexFileIds: [],
        picFileIds: [],
        mdStatus: '1',
        mdBelongTo: 'SUB',
        createTime: moment().locale('zh-cn').format('YYYY-MM-DD 00:00:00'),
        inProjectTime: moment().locale('zh-cn').format('YYYY-MM-DD 00:00:00'),
        mdCode: null
      }, // 表单
      selectedConfigPlanVisible: false,
      specificationModelArr: [],
      rules: {
        branchComId: [{ required: true, message: '请选择所属单位', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
        mdId: [{ required: true, message: '请选择设备名称', trigger: 'change' }],
        mdModelId: [{ required: true, message: '请选择规格型号', trigger: 'change' }],
        provideCompany: [{ required: true, message: '请选择提供单位', trigger: 'change' }],
        mdClassify: [{ required: true, message: '请选择设备分类', trigger: 'change' }],
        purpose: [{ required: true, message: '请输入设备用途', trigger: 'blur' }],
        appraisalType: [{ required: true, message: '请选择检定方式', trigger: 'change' }],
        beforeAppraisalDate: [{ required: true, message: '请选择上次检定时间', trigger: 'change' }],
        appraisalCycle: [{ required: true, message: '请输入检定周期', trigger: 'blur' }],
        appraisalStatus: [{ required: true, message: '请选择检定状态', trigger: 'change' }],
        inProjectTime: [{ required: true, message: '请选择进场时间', trigger: 'change' }],
      },
      verificationRecordQuery: {},// 检定记录查询参数
      provideCompanyParams: {} //获取提供单位的查询参数
    }
  },
  created() {
      const query = this.$route.query
      this.editModel = Number(query.editModel)
      //分包和自有获取检定记录
     this.verificationRecordQuery = {
        projectId: query.projectId
      }
      if (!query.mdOwnId) {
        this.verificationRecordQuery.mdProjectId = this.id
      } else {
        this.verificationRecordQuery.mdOwnId = query.mdOwnId
      }
  },
  mounted() {
    // 不为添加时请求详情
    if (this.editModel !== 2) {
      this.loading = true
      detailsItem({
        id: this.id
      }).then((res) => {
        this.loading = false
        this.form = res.data
        this.form.id= this.id
        this.form.annexFileIds = res.data.ownAnnexFileList || []
        this.form.picFileIds = res.data.ownPicFileList || []
        this.provideCompanyParams = {
          projectSet: [this.form.projectId], 
          detSet: [this.form.projectOrgId],
          _checked: this.form.projectId
        } 
      }).catch(() => {
        this.loading = false
      })
    } else {
      this.getMdCode()
      this.provideCompanyParams = {
        projectSet: [this.projectId], 
        detSet: [this.orgId],
        _checked: this.projectId
      } 
      const query = this.$route.query
      this.form.projectName = query.projectName
      this.form.projectId  = query.projectId
      // 设置分公司Id
      this.form.branchCompanyId = this.branchCompanyId
      const userInfo = this.$userInfo()
      this.form.creatorId = userInfo.id
      this.form.creatorName = userInfo.name
    }
  },
  computed: {
    // 表单列表
    formList() {
      return [
        {
          keyName: 'projectId',
          type: 'orgTree',
          label: '所属单位',
          isAutoSelectFirst:true,
          isNeedAuth:true,
          checkStrictly: true,
          disabled:true,
        },
        {
            type: Selector,
            keyName: 'mdId',
            label: '设备名称',
            disabled: this.editModel !== 2,
            attrs: {
              customApi: equipmentBsic.list,
              labelName: 'mdName',
              customQuery: {
                param: { status: 0 },
                pageNum: 1,
                pageSize: 0
              },
              dataValue: 'data.list',
            },
            getOption: (val) => {
              this.form.mdName = val?.mdName
              // 设置规格型号的值
              this.specificationModelArr = val && val.list.map(item => {
                  return {
                    label : item.specificationModel,
                    value: item.id
                  }
                })
            },
            change: (val) => {
              this.$set(this.form, 'mdModelId', undefined)
            }
        },
        {
            type: 'a-select',
            keyName: 'mdModelId',
            label: '规格型号',
            disabled: this.editModel !== 2,
            data: this.specificationModelArr,
            change: (item) => {
               let row = this.specificationModelArr.find(i => i.value === item)
               this.form.specificationModel = row?.label
            }
        },
        {
            type: 'a-input',
            keyName: 'mdCode',
            label: '设备编号',
            disabled: true,
        },
        {
            keyName: 'provideCompany',
            label: '提供单位',
            type: Selector,
            disabled: this.editModel === 0,
            attrs: {
              customApi: getSubcontractorsList,
              labelName: 'subcontractors',
              valueName: 'subcontractors',
              mode: "tags",
              customQuery: {
                queryType: '1',
                statusCode: '2',
                searchQuery: this.provideCompanyParams,
                dataValue: 'data',
              }
            },
            change: (val) => {
              this.form.provideCompany = val[val.length -1]
            },
        },
        {
            type: 'a-select',
            keyName: 'mdClassify',
            label: '设备分类',
            disabled: this.editModel === 0,
            data: equipmentClassArr,
        },
        {
            type: 'a-input',
            keyName: 'purpose',
            label: '设备用途',
            disabled: this.editModel === 0,
        },
        {
            type: 'a-input',
            keyName: 'projectPlanName',
            label: '所属配置计划',
            slot: true,
        },
        {
            type: 'a-input',
            keyName: 'materialCode',
            label: '机械设备编码（物资编码）',
            disabled: this.editModel === 0,
        },
        {
            type: 'a-input-number',
            keyName: 'purchasePrice',
            label: '采购单价',
            precision: 2,
            disabled: this.editModel === 0,
            attrs: {
              min: 0
            }
        },
        {
            type: 'a-input',
            keyName: 'manufacturerName',
            label: '品牌厂家名称',
            disabled: this.editModel === 0,
        },
        {
            type: 'a-input',
            keyName: 'manufacturerCode',
            label: '出厂编号',
            disabled: this.editModel === 0,
        },
        {
            type: 'a-select',
            keyName: 'appraisalType',
            label: '检定方式',
            data: checkType,
            disabled: this.editModel === 0,
        },
        {
            type: 'a-date-picker',
            keyName: 'beforeAppraisalDate',
            label: '上次检定日期',
            disabled: this.editModel === 0,
            attrs: {
                valueFormat: 'YYYY-MM-DD 00:00:00',
                format: 'YYYY-MM-DD',
                disabledDate: (current) => {
                  return current && current > moment().endOf('day')
                }
            },
            change: () => {
              this.setNextCheackTime()
            },
        },
        {
            type: 'a-input-number',
            keyName: 'appraisalCycle',
            label: '检定周期（月数）',
            precision: 0,
            disabled: this.editModel === 0,
            attrs: {
              min: 0,
              max: 10000000,
            },
            change: () => {
              this.setNextCheackTime()
            },
        },
        {
            type: 'a-date-picker',
            keyName: 'afterAppraisalDate',
            label: '下次检定日期',
            disabled: true,
            attrs: {
              valueFormat: 'YYYY-MM-DD 00:00:00',
              format: 'YYYY-MM-DD',
            }
        },
        {
            type: 'a-select',
            keyName: 'appraisalStatus',
            label: '检定状态',
            data: checkStatusArr,
            disabled: this.editModel === 0,
       },
       {
            type: 'a-select',
            keyName: 'mdStatus',
            label: '设备状态',
            disabled: true,
            data: dataFilter(equipmentStatusArr, ['1','2','3','4','5'])
        },
        {
            type: 'a-select',
            keyName: 'mdBelongTo',
            label: '设备归属',
            disabled: true,
            data: equipmentBelongToArr
        },
        {
            type: 'a-input',
            keyName: 'creatorName',
            label: '创建人',
            disabled: true,
        },
        {
            type: 'a-date-picker',
            keyName: 'createTime',
            label: '创建时间',
            disabled: true,
            attrs: {
              valueFormat: 'YYYY-MM-DD 00:00:00',
              format: 'YYYY-MM-DD',
            }
        },
        {
            type: 'a-date-picker',
            keyName: 'inProjectTime',
            label: '进场时间',
            disabled: this.editModel === 0,
            attrs: {
                valueFormat: 'YYYY-MM-DD 00:00:00',
                format: 'YYYY-MM-DD',
                disabledDate: (current) => {
                  return current && current > moment().endOf('day')
                }
            }
        },
        {
            type: 'a-date-picker',
            keyName: 'outProjectTime',
            label: '退场时间',
            disabled: true,
            attrs: {
                valueFormat: 'YYYY-MM-DD 00:00:00',
                format: 'YYYY-MM-DD',
            },
            hidden: this.editModel !== 0,
        },
        {
            type: 'a-textarea',
            keyName: 'remarks',
            disabled: this.editModel === 0,
            span: 24,
            label: '备注',
        },
        {
            label: '设备图片',
            keyName: 'picFileIds',
            type: UploadList,
            span: 24,
            attrs: {
              businessCode: 'PM44',
              uploadType: 'image',
              isMultiple: true,
              editModel: this.editModel,
              uploadArrys: this.form.picFileIds || []
            },
        },
        {
            keyName: 'annexFileIds',
            type: UploadList,
            span: 24,
            label: '附近上传',
            disabled: this.editModel == 0,
            attrs: {
                businessCode: 'PM44',
                uploadArrys: this.form.annexFileIds || [],
                isShow: this.editModel == 0 ? false : true,
                isClose: this.editModel == 0 ? false : true,
            },
            fileArrysData: (e) => {
              this.fileArrysData('annexFileIds', e)
            }
        },
      ]
    }
  },
  methods: {
    closePage() {
      // 存在业务ID。则返回到记录设备归还页面
      if(this.$route.query.isReturnUpperLevel) {
        this.$router.push({
          name: 'recordDeviceReturnManagementInfo',
       })
      } else{
        this.$multiTab.close()
      }
    },
    //获取设备编号
    async getMdCode() {
      let res = await generateMdCode({projectId: this.projectId})
      if (res.data) {
        this.form.mdCode= res.data
      }
    },
    // 设置下次检定时间
    setNextCheackTime() {
      if (this.form.beforeAppraisalDate && this.form.appraisalCycle) {
        const beforeAppraisalDate = new Date(this.form.beforeAppraisalDate)
        const time = beforeAppraisalDate.setDate(beforeAppraisalDate.getDate() + (this.form.appraisalCycle*30))
        this.form.afterAppraisalDate = moment(time).format('YYYY-MM-DD 00:00:00')
      }
    },
    // 获取上传的文件内容
    fileArrysData(name, e) {
      this.$set(this.form, name, [...e])
    },
    // 当关闭弹窗时，同步selectedConfigPlanVisible的值
    handelShow(e) {
      this.selectedConfigPlanVisible = e
    },
    // 打开所属配置计划弹窗
    chioseBtn() {
      this.selectedConfigPlanVisible = true
    },
    // 获取所选中的配置计划
    handleModalClick(e) {
      this.form.projectPlanId = e.projectPlanId
      this.form.projectPlanName = e.mdName
      this.form.configProjectId = e.configProjectId
      this.form.versionId = e.versionId
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let url = [editItem, addItem][this.editModel - 1] // 根据操作切换url地址
      // 校验表单
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          // 提交表单
          this.loading = true
          let params = this.$clone(this.form)
          params.picFileIds =  params.picFileIds?.length ? params.picFileIds.map((item) => item.commonId) : [];
          params.annexFileIds =  params.annexFileIds?.length ? params.annexFileIds.map((item) => item.commonId) : [];
          url(params)
            .then((res) => {
              this.loading = false
              if (res.code === '0' || res.data.code === '0') {
                this.$message.success('提交成功！')
                this.$multiTab.close()
              }
            })
            .catch(() => {
              this.loading = false
            })
        }
      })
    }
  }
}
</script>